<template>
  <el-form
    ref="formRef"
    :rules="rules"
    :inline="true"
    :model="formInline"
    class="demo-form-inline"
    label-width="auto"
    :disabled="control.isLook"
  >
    <el-form-item label="题目" label-position="right" prop="title">
      <el-input
        v-model="formInline.title"
        type="textarea"
        style="width: 220px"
        clearable
      />
    </el-form-item>
    <el-form-item label="第一作者" prop="firstAuthor">
      <el-input v-model="formInline.firstAuthor" clearable />
    </el-form-item>
    <el-form-item label="其它作者" prop="otherAuthor">
      <el-input v-model="formInline.otherAuthor" clearable />
    </el-form-item>
    <el-form-item label="出版社" prop="press">
      <el-input v-model="formInline.press" clearable />
    </el-form-item>
    <el-form-item label="会议名称" prop="confName">
      <el-input v-model="formInline.confName" clearable />
    </el-form-item>
    <el-form-item label="会议地点" prop="spot">
      <el-input v-model="formInline.spot" clearable />
    </el-form-item>
    <el-form-item label="会议时间" prop="confTime">
      <el-col :span="14">
        <el-date-picker
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="开始日期"
          v-model="formInline.confTime"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="会议级别" prop="level">
      <el-select v-model="formInline.level" clearable placeholder="请选择">
        <el-option label="国内" value="国内" />
        <el-option label="国外" value="国外" />
      </el-select>
    </el-form-item>
    <el-form-item label="奖励类别" prop="type">
      <el-tree-select
        v-model="formInline.type"
        :data="accountTreeLoc"
        :render-after-expand="false"
        @change="handleNodeChange"
        clearable
        placeholder="请选择"
      />
    </el-form-item>
    <el-form-item label="字数(千)" prop="textNumber">
      <el-input-number
        v-model="formInline.textNumber"
        :precision="3"
        :step="0.001"
        :max="1000"
        style="width: 220px"
      />
    </el-form-item>
    <el-form-item label="科研奖励(万)" prop="bonus">
      <el-input-number
        v-model="formInline.bonus"
        :precision="4"
        :step="0.0001"
        :max="10000"
        style="width: 220px"
      />
    </el-form-item>
    <el-form-item label="业绩点" prop="point">
      <el-input v-model="formInline.point" clearable />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="formInline.remark" clearable />
    </el-form-item>
    <el-form-item>
      <el-upload
        ref="upload"
        v-model:file-list="fileList"
        class="upload-demo"
        action=""
        :auto-upload="false"
        :http-request="_uploadFile"
        accept=".pdf"
        :limit="1"
        :on-exceed="handleExceed"
        style="height: 100px"
      >
        <el-button type="primary" style="margin-top: 33px">上传附件</el-button>
      </el-upload>
    </el-form-item>
  </el-form>
  <div class="dialog-footer" v-if="control.isAdd">
    <el-button type="primary" @click="_save()" style="margin-left: 540px"
      >确认添加</el-button
    >
    <el-button
      type="primary"
      @click="
        control.centerDialogVisible = false;
        control.isLook = true;
      "
    >
      关闭
    </el-button>
  </div>
  <div class="dialog-footer" v-else-if="!control.isLook">
    <el-button
      type="primary"
      v-if="!control.isLook"
      @click="_update()"
      style="margin-left: 540px"
      >确定修改</el-button
    >
    <el-button
      type="primary"
      @click="
        control.centerDialogVisible = false;
        control.isLook = true;
      "
    >
      关闭
    </el-button>
  </div>
</template>
<script setup lang="ts">
import * as $accountApi from "@/api/sci/account";
import {
  ElMessage,
  FormRules,
  UploadProps,
  UploadRequestHandler,
  UploadRequestOptions,
  UploadUserFile
} from "element-plus";
import { defineProps, toRefs, ref, onMounted } from "vue";
import * as $fileApi from "@/api/sci/file";
import * as $conferencefApi from "@/api/sci/paper/conference";
// 自定义 modelValue 的事件名称
const props = defineProps({
  formInline: Object,
  control: Object,
  accountTree: Array,
  hasPermission: Function,
  _loadQueryPage: Function,
  __save: Function
});
// const emit = defineEmits(["update:formInline", "__save", "hasPermission"]);
//  "_loadQueryPage",
// 简化后的树形结构类型
interface treeNode {
  label: string;
  value: string;
  point: string;
  bonus: number;
  children: treeNode[]; // 递归的子节点
}
// 手动上传赋空值对象
const upload = ref(null);
//校验规则
const rules: FormRules = {
  title: [
    { required: true, message: "请输入题目", trigger: "blur" },
    { max: 80, message: "题目长度不能超过80个字符", trigger: "blur" }
  ],
  firstAuthor: [
    { required: true, message: "请输入第一作者", trigger: "blur" },
    { max: 30, message: "第一作者长度不能超过30个字符", trigger: "blur" }
  ],
  otherAuthor: [
    { max: 80, message: "其他作者长度不能超过80个字符", trigger: "blur" }
  ],
  press: [
    { required: true, message: "请输入出版社", trigger: "blur" },
    { max: 80, message: "出版社长度不能超过80个字符", trigger: "blur" }
  ],
  confName: [
    { required: true, message: "请输入会议名称", trigger: "blur" },
    { max: 80, message: "会议名称长度不能超过80个字符", trigger: "blur" }
  ],
  spot: [
    { required: true, message: "请输入会议地点", trigger: "blur" },
    { max: 30, message: "会议地点长度不能超过30个字符", trigger: "blur" }
  ],
  confTime: [{ required: true, message: "请输入会议时间", trigger: "blur" }],
  level: [{ required: true, message: "请选择会议级别", trigger: "change" }],
  type: [{ required: true, message: "请选择奖励类别", trigger: "change" }],
  point: [
    { required: true, message: "请输入业绩点", trigger: "blur" },
    { max: 80, message: "备注长度不能超过80个字符", trigger: "blur" }
  ],
  remark: [{ max: 80, message: "备注长度不能超过80个字符", trigger: "blur" }]
};
//数据初始化
onMounted(() => {
  _loadAccountTree();
});
const _loadAccountTree = () => {
  if (!props.accountTree) {
    $accountApi.treeList("PaperConf").then(res => {
      accountTreeLoc.value = transformData(res.result[0].children);
    });
    resetForm(false, {}, false);
  } else {
    accountTreeLoc.value = props.accountTree;
  }
};

const { formInline } = toRefs(props);
const { control } = toRefs(props);
// const { accountTree } = toRefs(props);
//核算树
const accountTreeLoc = ref();
// 根据ID查找节点
const findNodeById = (nodes: any[], id: string): any | null => {
  for (const node of nodes) {
    if (node.value === id) {
      return node; // 找到节点
    }
    if (node.children && node.children.length > 0) {
      const result = findNodeById(node.children, id);
      if (result) return result; // 递归查找子节点
    }
  }
  return null; // 如果没有找到
};
// 当前选中的节点数据
const selectedNode = ref<treeNode | null>(null);
// 处理核算选择事件
const handleNodeChange = (value: string) => {
  selectedNode.value = findNodeById(accountTreeLoc.value, value);
  formInline.value.type = selectedNode.value.label;
  formInline.value.bonus = selectedNode.value.bonus;
  formInline.value.point = selectedNode.value.point;
};

// transformData 函数：将原始数据转换为简化的格式
const transformData = (data: any[]): any[] => {
  return data.map(item => ({
    label: item.title,
    value: item.id,
    point: item.point,
    bonus: item.bonus,
    children:
      item.children && item.children.length > 0
        ? transformData(item.children)
        : []
  }));
};
// const type = "PaperConf";
const formRef = ref(null);
//上传文件功能
const fileList = ref<UploadUserFile[]>([]); //文件上传列表
//更新数据请求
const _update = () => {
  formRef.value.validate(valid => {
    if (valid) {
      // 校验成功，继续执行保存操作
      if (fileList.value.length === 0) {
        __update();
      } else {
        upload.value.submit();
      }
    } else {
      // 校验失败，发送提示
      ElMessage.error("表单校验失败，请检查输入");
    }
  });
};
//更新数据请求
const __update = () => {
  // console.log(formInline.path);
  $conferencefApi
    .update(formInline.value.id, formInline.value)
    .then(() => {
      ElMessage({
        message: "添加成功",
        type: "success"
      });
    })
    .catch(err => {
      ElMessage({
        message: "添加失败，请稍后再试" + err,
        type: "error"
      });
    })
    .finally(() => {
      // emit("_loadQueryPage");
      props._loadQueryPage();
      // resetValidate();
      control.value.centerDialogVisible = false;
    });
};
//超出文件数量限制
const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};
//上传文件具体实现
const _uploadFile: UploadRequestHandler = (param: UploadRequestOptions) => {
  return new Promise<void>((resolve, reject) => {
    const file = param.file;

    if (!(file instanceof File)) {
      console.error("上传的对象不是文件:", file);
      ElMessage.error("请选择一个有效的文件。");
      reject(new Error("无效的文件"));
      return;
    }
    if (formInline.value.path !== "") {
      deleteExistingFile();
    }

    // 创建FormData对象，准备上传
    const Form = new FormData();
    Form.append("file", file);

    $fileApi
      .uploadFile(Form)
      .then(res => {
        formInline.value.path = res.message;
        if (control.value.isAdd == false) __update();
        else props.__save();
        resolve(); // 上传成功，调用 resolve
      })
      .catch(error => {
        console.error("上传文件时出错:", error);
        ElMessage.error("文件上传失败，请重试。");
        reject(error); // 上传失败，调用 reject
      });
  });
};

//添加会议论文请求
const _save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      // 校验成功，继续执行保存操作
      if (fileList.value.length === 0) {
        // diaowai__save();
      } else {
        upload.value.submit();
      }
    } else {
      // 校验失败，发送提示
      ElMessage.error("表单校验失败，请检查输入");
    }
  });
};
// 删除已有文件的处理
const deleteExistingFile = () => {
  $fileApi
    .deleteFile(formInline.value.path)
    .then(res => {
      if (res.success) ElMessage.success("文件覆盖成功。");
    })
    .catch(error => {
      console.error("上传文件时出错:", error);
      ElMessage.error("文件覆盖失败，请重试。");
    });
};

// 通用函数，用于重置表单状态
const resetForm = (isAddNew = true, row = {}, isEditable = true) => {
  resetValidate();
  // 重置 formInline 数据
  Object.keys(formInline.value).forEach(key => {
    formInline.value[key] = key === "textNumber" || key === "bonus" ? 0 : "";
  });
  // 清空 fileList
  fileList.value = [];
  // 设置新增或查看模式
  control.value.isAdd = isAddNew;
  control.value.isLook = isEditable; // 根据 isEditable 决定是否可以编辑
  // 传入的行数据（如果是更新或查看）
  if (!isAddNew) {
    Object.assign(formInline.value, row);
  }
};
const resetValidate = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  } // 清除之前的校验结果
};
defineExpose({ resetForm });
</script>
